import asyncio
import socket
import traceback

from asyncio import Queue






class GeSocketClient:


    def __init__(self, server_ip, server_port):
        self.server_ip = server_ip
        self.server_port = server_port
        self.socket_client = None
        self.msg_queue:Queue = None


    async def keep_send(self):
        while True:
            try:
                if self.msg_queue.qsize() == 0:
                    await asyncio.sleep(1)
                else:
                    item = await self.msg_queue.get()
                    self.send_command(item)
                    self.msg_queue.task_done()
                    self.receive()
            except:
                err = traceback.format_exc()
                print(f"------error: {err}")


    def send_data(self,msg):
        if self.msg_queue is not None:
            self.msg_queue.put_nowait(msg)

    async def mock_data(self):
        print(f"-------mock_data--------")
        index = 1
        while True:
            if self.msg_queue is not None:
                self.msg_queue.put_nowait(f"{index}")
                print(f"-------mock_data： {index}")
            index += 1
            await asyncio.sleep(2)

    def receive(self):
        if self.socket_client is not None:
            # 接收服务器返回的数据
            data = self.socket_client.recv(1024)
            print(f"-------接收： {data}")

    async def connect(self):
        tasks = []
        try:
            client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            client_socket.connect((self.server_ip, self.server_port))
            print(f"------连接成功-------")
            self.socket_client = client_socket
            self.msg_queue = asyncio.Queue()

            tasks.append(asyncio.create_task(self.keep_send()))
            # tasks.append(asyncio.create_task(self.mock_data()))

            await asyncio.gather(*tasks)
        except Exception:
            for task in tasks:
                task.cancel()
            error_info  = traceback.format_exc()
            print(f"---------error:{error_info}")
            pass

    def hex_to_bytes(self, input_string):
        # 将字符串编码为字节数组
        str_len = len(input_string)
        arr_count = int(str_len / 2)
        arr = bytearray()
        for i in range(0, arr_count):
            arr = arr + bytes.fromhex(input_string[2 * i:(2 * i) + 2])
        return arr

    def send_command(self, params):
        try:
            data = self.hex_to_bytes(params)
            self.socket_client.send(data)
            print(f"---------发送: {data}")
        except:
            error_info = traceback.format_exc()
            print(f"-----error_info: {error_info}")




async def main():
    # 设置服务器的IP地址和端口号
    server_ip = '192.168.1.253'
    server_port = 1030
    try:
        client = GeSocketClient(server_ip, server_port)
        await client.connect()
    except ConnectionRefusedError:
        print('连接被拒绝，请确认服务器是否已启动')


if __name__ == '__main__':
    asyncio.run(main())
